Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
Javascript nullish coalescing chained with "or"

I'm making use of Javascript's "??" operator to assign a default value when the variable is undefined along with "||" when I don't want an undefined value or 0.

For example, the following will prefer "a" when defined or resort to "b".
Then it would prefer 1 when the coalesced value was undefined or 0:

var a, b;
console.log((a ?? b) || 1); // prints "1"

However, the following tweak presents a compilation error.
I'd expect it to either print "1" or "undefined" depending on operation precedence:

var a, b;
console.log(a ?? b || 1); // Uncaught SyntaxError: missing ) after argument list"

Lastly, this compiles and runs but with the caveat that "0" would be an accepted value:

var a, b;
console.log(a ?? b ?? 1); // prints "1"

What's the nuance that I'm missing here?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

According to the documentation, you can't chain the nullish coalescing operator with AND or OR:

MDN:

It is not possible to combine both the AND (&&) and OR operators (||) directly with ??. A SyntaxError will be thrown in such cases.

null || undefined ?? "foo"; // raises a SyntaxError
true || undefined ?? "foo"; // raises a SyntaxError

However, providing parenthesis to explicitly indicate precedence is correct:

(null || undefined) ?? "foo"; // returns "foo"

I found this blog post a helpful resource in thinking through why.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda